<#
	#   It is recommended to test the script on a local machine for its purpose and effects. 
	#   Endpoint Central will not be responsible for any 
	#   damage/loss to the data/setup based on the behavior of the script.

	#   Description: Script to delete same extension file under the C Drive except users folders
	#   Configuration Type - Computer
	#	Arguments 
		".txt"		
#>

$extension = args[0]

# Get all logical disks on the machine
$drives = Get-WmiObject -Class Win32_LogicalDisk | Where-Object { $_.DriveType -eq 3 }

# Flag to check if any matching files are found
$filesFound = $false

# Iterate through each drive and search for files with the extension
foreach ($drive in $drives) {
    $rootDirectory = $drive.DeviceID + "\"

    # Get all files with the specified extension in the current drive, including hidden files
    $files = Get-ChildItem -Path $rootDirectory -Filter "*$extension" -Recurse -File -Force -ErrorAction SilentlyContinue

    # Delete the matching files
    if ($files.Count -gt 0) {
        $files | ForEach-Object {
            Remove-Item -Path $_.FullName -Force -ErrorAction SilentlyContinue
            Write-Host "Deleted File: $($_.FullName)"
        }

        # Set the flag to true as matching files are found and deleted
        $filesFound = $true
    }
}

# Search in the AppData folder
$appDataPath = [Environment]::GetFolderPath('ApplicationData')

# Get all files with the specified extension in the AppData folder and its subdirectories, including hidden files
$appDataFiles = Get-ChildItem -Path $appDataPath -Filter "*$extension" -Recurse -File -Force -ErrorAction SilentlyContinue

# Delete the matching files in the AppData folder
if ($appDataFiles.Count -gt 0) {
    $appDataFiles | ForEach-Object {
        Remove-Item -Path $_.FullName -Force -ErrorAction SilentlyContinue
        Write-Host "Deleted File: $($_.FullName)"
    }

    # Set the flag to true as matching files are found and deleted
    $filesFound = $true
}

# Display a message if no matching files are found
if (-not $filesFound) {
    Write-Host "No files with the extension $extension found."
}